import pandas as pd
import re
import time
import os
import shutil
from split_utils import rule_list_1



def split_1(operate_dir):

    # 读取配置文件 --------------------------------------
    source_author_col = '作者'
    # -------------------------------------------------

    # 检测excel数量，只能放一个，当只有一个excel时，提取它的路径excel_path -------
    print('检查路径下的文件格式...')
    excel_name = None
    excel_count = 0
    file_list = os.listdir(operate_dir)
    for file in file_list:
        if file.endswith('.xlsx') or file.endswith('.xlx'):
            excel_count += 1
            excel_name = file
    if excel_count == 0:
        input('文件夹下没有excel，按任意键退出...')
        raise Exception(0)
    if excel_count > 1:
        input('只能放一个excel，按任意键退出...')
        raise Exception(0)

    # print(excel_name)
    # raise Exception(1212)
    # ----------------------------------------------------------------------
    # print(excel_path)
    # print(img_dir)

    # 读取excel ----------------------------------------
    excel_path = os.path.join(operate_dir, excel_name)
    # print(excel_path)
    try:
        df = pd.read_excel(excel_path)
        df = df.where(df.notnull(), None)
    except Exception as e:
        print(e)
        print('文件不存在或已损坏...')
        input('按任意键退出...')
        raise Exception('123')
    # -------------------------------------------------

    # 备份原始excel表 --------------------------------------------------------------
    print('备份excel...')
    bak_dir = '作者拆分前的备份'
    file_list = os.listdir(operate_dir)
    if bak_dir not in file_list:
        os.makedirs(os.path.join(operate_dir, bak_dir))
    bak_excel_path = os.path.join(os.path.join(operate_dir, bak_dir), excel_name)
    shutil.copyfile(excel_path, bak_excel_path)
    # -----------------------------------------------------------------------------

    # --------------------------------
    # all_nomatch_list = []  # 未匹配到的数据
    all_split_list = []  # 拆分后的结果列
    all_no_split_author_flag = []   # 未被拆分的作者标记为True
    # all_countryside_list = []  # 国别/年代
    # all_name_list = []  # 姓名
    # all_zlfs_list = []  # 著录方式
    # all_alias_list = []  # 别名
    # --------------------------------

    for i in range(df.shape[0]):

        # 源作者
        try:
            source_author = str(df.loc[i, source_author_col])
        except Exception as e:
            print(e)
            print('excel中好像没有“作者”这一列')
            input('按任意键退出...')
            raise Exception('123')

        print(i, source_author)

        if not source_author:
            all_split_list.append(None)
            all_no_split_author_flag.append(None)
        else:
            source_author = str(source_author)

            # 调用不同的拆分方法 -------------------------------------------------------------------------
            split_list = re.split(rule_list_1[1], source_author)
            split_list = [split for split in split_list if split != '']
            # ------------------------------------------------------------------------------------------

            print(i, split_list)
            all_split_list.append(';'.join(split_list))

            # 没有被拆分的原题名标记 ---------
            if len(split_list) <= 1:
                no_split_author_flag = True
            else:
                no_split_author_flag = False

            all_no_split_author_flag.append(no_split_author_flag)
            # ----------------------------

    # 打印拆分结果 ------------------
    print('all_split_list: {}'.format(all_split_list))
    print('all_no_split_author_flag: {}'.format(all_no_split_author_flag))
    # -----------------------------

    # 保存拆分结果 ----------------------------
    df.loc[:, '<作者>拆分后元数据内容'] = all_split_list
    df.loc[:, '<作者>程序{}无拆分记号'.format(1)] = all_no_split_author_flag
    df.to_excel(excel_path, index=0)
    # ---------------------------------------



if __name__ == '__main__':
    operate_dir = r'C:\Users\cxstar46\Desktop\正则表达式作者拆分测试'
    split_1(operate_dir)
